<?php
/**
 * 《语音网关》
 *
 * @author 孙晓晔
 * @version $Id: Exten.class.php 804 2009-12-30 10:05:41Z sunxy $
 */

require_once(dirname(__FILE__) . '/Info.class.php');

class Sip extends Info {
	public $tbl = 'fy.sip';

	public $status = array(
		'-' => '请选择',
		'1' => '在线',
		'2' => '离线',
		
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'user' => '分机',
		'host' => '地址',
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $recording = array(
		'-' => '请选择',
		'Always' => '是',
		'Never' => '否',		
	);

	public $groupby = array(
		'-' => '请选择',
		'host' => '地址',
		'port' => '端口',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/03/06 11:35:48 $';
		$request['revision'] = '$Revision: 1.2 $';
			
		parent::__construct($request);
	}

	/**
	 * 预处理
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('recording_option', $this->recording);
	}

	/**
	 * 首页
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function layout($controller, $request) {

		$controller->display($request, 'priv');
		return true;
	}

	/**
	 * 查找
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);
			
		$controller->display($request, 'emp/sip/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$name_s = $request['name_s'];
		$exten_s = $request['exten_s'];

		$where = " WHERE 1=1";

		if (!empty($name_s)) {
			$where .= " AND name like '" . $name_s . "%'";
		}

		if (!empty($exten_s) && $exten_s <> '-') {
			$where .= " AND user = '" . $exten_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$this->peers = $this->peers();

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];

				$row['emp_t'] = $this->name($row['user']);
				$row['status_t'] = $this->status[$row['status']];

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'emp/sip/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-100 day'));
		$controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'emp/sip/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'host');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function update($controller, $request) {
		$this->pretreat($controller);
			
		$controller->display($request, 'emp/exten/cf');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function updatePost($controller, $request) {
		$this->pretreat($controller);

		$exten = $request['exten'];
		$to = $request['to'];
		if (preg_match("/^6/i", $exten)) {
			$am = astman('ns');
		} else if (preg_match("/^8/i", $exten)) {
			$am = astman('sj');
		} else if (preg_match("/^2/i", $exten)) {
			$am = astman('fy');
		}

		if (empty($to)) {
			$ret = $am->database_del('CF', $exten);
		} else {
			$ret = $am->database_put('CF', $exten, $to);
		}

		$am->disconnect();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
			
		$this->findPost($controller, $request);
		return true;
	}

	/**
	 * 录音设置
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function recording($controller, $request) {
		$this->pretreat($controller);

		$exten = $request['exten'];

		if (preg_match("/^6/i", $exten)) {
			$am = astman('ns');
		} else if (preg_match("/^8/i", $exten)) {
			$am = astman('sj');
		} else if (preg_match("/^2/i", $exten)) {
			$am = astman('fy');
		}

		$ret = $am->database_get('AMPUSER', $exten . "/recording");

		$data['exten'] = $exten;

		$recording = explode("|", $ret);
		$data['out'] = substr($recording[0],4);
		$data['in'] = substr($recording[1],3);

		$controller->assign_by_ref('result', $data);

		$am->disconnect();
			
		$controller->display($request, 'emp/sip/recording');
		return true;
	}

	/**
	 * 录音设置
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function recordingPost($controller, $request) {
		$this->pretreat($controller);

		$exten = $request['exten'];
		if (preg_match("/^6/i", $exten)) {
			$am = astman('ns');
		} else if (preg_match("/^8/i", $exten)) {
			$am = astman('sj');
		} else if (preg_match("/^2/i", $exten)) {
			$am = astman('fy');
		}

		$in = $request['in'];
		$out = $request['out'];
		if (empty($in) || $in == '-') {
			$in = "Adhoc";
		}

		if (empty($out) || $out == '-') {
			$out = "Adhoc";
		}

		$fmt = "out=%s|in=%s";
		$cmd = sprintf($fmt, $out, $in);

		$ret = $am->database_put('AMPUSER', $exten . '/recording', $cmd);
		// echo $ret;
		$am->disconnect();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
			
		$this->findPost($controller, $request);
		return true;
	}

	function t($controller, $request) {

		$am = astman('sj');

		// $am->Originate('SIP/6595', '913760120595', 'tt', '1', NULL, NULL, 8000, '6595', NULL, NULL, NULL, NULL);

		// $ret = $am->Status('SIP/6595');
		// $ret = $am->database_show('CW 6595');
		// $ret = $am->Command('sip show peer 6595');
		// $ret = $am->Command('sip show peer 8417');
		// $data = $ret['data'];

		// echo $this->status($data);

		$ret = $am->database_get('AMPUSER', '8008/recording');
		echo($ret);

		$am->disconnect();
		// logdate($controller, $request);
		return true;
	}

	function peer($controller, $request) {
		$am = astman('ns');

		// $am->Originate('SIP/6595', '913760120595', 'tt', '1', NULL, NULL, 8000, '6595', NULL, NULL, NULL, NULL);

		// $ret = $am->Status('SIP/6595');
		// $ret = $am->database_show('CW 6595');
		// $ret = $am->Command('sip show peer 6595');
		$ret = $am->Command('sip show peer 6765');
		// print_r($ret);

		$data = $ret['data'];

		echo $this->useragent($data);

		$am->disconnect();
		logdate($controller, $request);
		return true;
	}

	function useragent($data) {
		$aa = preg_split("/[\\n]+/i", $data);
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 5) {
				continue;
			}

			if (preg_match("/^Useragent/", $buf)) {
				$pos = strpos($buf, ":");
				return trim(substr($buf, $pos + 1));
			}
		}

		return '';
	}

	function _emp_exten($exten) {
		require_once(dirname(__FILE__) . '/../emp/Exten.class.php');
		$aa = new Exten();
		
		return $aa->_view_exten($exten);
	}

	
	
	function c($controller, $request) {
		
		$fd = fopen("/home/sunxy/sip.channels", "r");
		$i = 0;
		while (!feof($fd)) {
			$s = trim(fgets($fd));
			$i++;
			
			if ($i < 3) {
				continue;
			}			
			
			if (preg_match("/(\d+) active channels/i", $s, $m)) {
				print_r($m);
				// echo sprintf("%s\n", $s);
				continue;
			}
			
			if (preg_match("/(\d+) active call/i", $s, $m)) {
				print_r($m);
				// echo sprintf("%s\n", $s);
				break;
			}
			
			$a = preg_split("/[\s,]+/", $s);			
			print_r($a);
			
			echo sprintf("%s\n", $s);
		}

		logdate($controller, $request);
		return true;
	}
	
	function d($controller, $request) {
		
		$fd = fopen("/home/sunxy/sip.channel", "r");
		
		$ret = array();
		while (!feof($fd)) {
			$s = trim(fgets($fd));
			if (strlen($s) < 5) {
				continue;
			}
			
			if (preg_match("/level 1: (\\S+)=(.+)/i", $s, $m)) {
				// print_r($m);
				$ret[$m[1]] = $m[2];
			}

			// $a = preg_split("/[\\s,]+/", trim($s));			
			// echo sprintf("%s\n", $s);
		}
		
		print_r($ret);

		logdate($controller, $request);
		return true;
	}

	function status_1($exten) {
		$db = newdb($this->dsn_r);
		$fmt = "select id, code, mobile, exten, status from %s where exten = '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp, $exten);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// print_r($row);
			if ($row['status'] == '1' || $row['status'] == '8') {
				return true;
			}
		}

		return false;
	}

	function name($exten) {
		$db = newdb($this->dsn_r);
		$fmt = "select id, code, name, mobile, exten, status from %s where exten = '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp, $exten);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// print_r($row);
			if ($row['status'] == '1' || $row['status'] == '8') {
				return $row['name'];
			}
		}

		return '';
	}

	function content($host) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE host = '%s'";
		$sql = sprintf($fmt, $this->tbl, $host);
		debug($sql);
		$result = $db->query($sql);
		$ret = "";
		while ($row = $db->fetch_array($result)) {
			$fmt = "%s[%s]";
			$s = sprintf($fmt, $this->name($row['user']), $row['user']);
			$ret .= ", " . $s;
			$ua = $row['ua'];
		}

		$ret .= ", " . $ua;

		return ltrim($ret, ",");
	}

	function b($controller, $request) {
		$am = astman('sj');
		$ret = $am->Command('sip show peers');

		$data = $ret['data'];
		// echo $data;

		$aa = preg_split("/[\\n]+/i", $data);

		$db = newdb($this->dsn_w);

		$fmt = "truncate table %s";
		$sql = sprintf($fmt, $this->tbl);
		// echo $sql . "\n";
		// $db->query($sql);

		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 5) {
				continue;
			}

			if (!preg_match("/^\d/", $buf)) {
				continue;
			}

			$a = preg_split("/[\\s,|\/]+/", $buf);
			// print_r($a);
			$user = $a[0];
			$host = $a[2];
			$port = $a[6];

			$status = '2';
			if ($a[7] == 'OK') {
				$status = '1';
			}

			if (!preg_match("/^\d/", $host)) {
				continue;
			}

			$ret = $am->Command('sip show peer ' . $user);
			$data = $ret['data'];

			$ua = $this->useragent($data);

			$fmt = "REPLACE INTO %s(user, host, port, ua, status, createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', now(), now())";
			$sql = sprintf($fmt, $this->tbl, $user, $host, $port, $ua, $status);
			echo $sql . "\n";
			$db->query($sql);

			$fmt = "UPDATE %s SET category = '2' where ip = '%s'";
			$sql = sprintf($fmt, Constant::tbl_emp_mac, $host);
			$db->query($sql);
		}

		$am->disconnect();

		logdate($controller, $request);
		return true;
	}
}
?>
